<template>
  <el-container class="main_con">
    <div class="filter_con nopt">
      <div class="filter_area">
        <!-- <el-input class="serach_input mr_15" size="medium" placeholder="商品名称" style="width:300px;"></el-input> -->
        <el-input size="medium" v-model="obj.order_no" placeholder="请输入订单编号" class="mr_15 mt_15" style="width:400px;">
          <!-- <el-select v-model="obj.type" slot="prepend" placeholder="请选择" style="width:130px;">
            <el-option v-for="item in type" :key="item.value" :label="item.label" :value="item.value"></el-option>
          </el-select> -->
        </el-input>

        <label class="mr_15 mt_15">状态</label>
        <el-select v-model="obj.status" size="medium" placeholder="请选择" class="mr_15 mt_15">
          <el-option v-for="item in status" :key="item.value" :label="item.label" :value="item.value"></el-option>
        </el-select>

        <label class="mr_15 mt_15">创建时间</label>
        <date-picker size="medium" @change="getTime" class="mr_15 mt_15"></date-picker>
        <el-button class="mr_15 mt_15" @click="searchList" size="medium">搜索</el-button>
        <!-- <el-button v-has class="mr_15 mt_15" @click="exportorder" size="medium">导出</el-button> -->
      </div>
    </div>
    <div class="list_con" v-loading="isLoading">
      <div class="orderlist">
        <div class="order_head">
          <table cellspacing="0" cellpadding="0" width="100%">
            <colgroup>
              <col />
              <col width="150" />
              <col width="180" />
              <col width="180" />
              <col width="150" />
              <col width="130" />
              <col width="200" />
            </colgroup>
            <tbody>
              <tr>
                <td>商品</td>
                <td>单价/数量</td>
                <td>买家</td>
                <td>实付款</td>
                <td>支付/配送</td>
                <td>状态</td>
                <td>操作</td>
              </tr>
            </tbody>
          </table>
        </div>

        <div class="order" v-for="(item, i) in list" :key="i">
          <div class="header">
            <div class="txt">
              <div class="info">下单时间：{{ item.create_time }}</div>
              <div class="info">订单编号：{{ item.order_no }}</div>

              <div class="info"><el-button type="text" @click="doCopy(item.order_no)">复制</el-button></div>
              <div class="info">
                订单来源：
                <i title="微信小程序" v-if="item.source == 1" class="weixin el-sc-xiaochengxu"></i>
                <i title="微信公众号" v-if="item.source == 2" class="weixin el-sc-weixin4"></i>
              </div>

              <div class="info">
                <el-tooltip placement="bottom-start">
                  <div class="one_line">
                    <span style="cursor: pointer">买家备注：{{ item.remake }}</span>
                  </div>
                  <div slot="content" style="width: 400px;line-height: 1.5;">买家备注： {{ item.remake }}</div>
                </el-tooltip>
              </div>
            </div>
          </div>
          <div class="content">
            <table cellspacing="0" cellpadding="1" border="1" bordercolor="#dcdfe6" style="border-collapse:collapse;" width="100%">
              <colgroup>
                <col />
                <col width="150" />
                <col width="180" />
                <col width="180" />
                <col width="150" />
                <col width="130" />
                <col width="200" />
              </colgroup>
              <tbody>
                <tr v-for="(sitem, l) in item.orderCommodity" :key="l">
                  <td>
                    <div class="pro">
                      <div class="img"><vimage style="width: 80px; height: 80px;" :src="sitem.goods.master" fit="fit"></vimage></div>
                      <div class="txt">
                        <div class="name">
                          <span :class="'t' + sitem.goods.type">{{ sitem.goods.type == 0 ? '实' : '虚' }}</span>
                          {{ sitem.goods.name }}
                        </div>
                        <div class="class">{{ sitem.pvs_value_new }}</div>
                      </div>
                    </div>
                  </td>
                  <td>
                    {{ sitem.sell_price || sitem.goods.sell_price }}积分
                    <br />
                    X{{ sitem.count }}
                  </td>

                  <td v-if="item.orderCommodity.length == 1 || l == 0" :rowspan="item.orderCommodity.length">
                    <el-tooltip v-if="item.order_type == 1" :content="'收货地址：' + item.address" placement="bottom-start">
                      <span style="cursor: pointer">
                        {{ item.consignee }}
                        <br />
                        {{ item.iphone }}
                      </span>
                    </el-tooltip>
                    <span style="cursor: pointer" v-else>
                      {{ item.consignee }}
                      <br />
                      {{ item.iphone }}
                    </span>
                  </td>
                  <td v-if="item.orderCommodity.length == 1 || l == 0" :rowspan="item.orderCommodity.length">{{ item.money }}积分</td>
                  <!-- <td v-if="item.orderCommodity.length == 1 || l == 0" :rowspan="item.orderCommodity.length">后台确认<br/>快递</td> -->
                  <td v-if="item.orderCommodity.length == 1 || l == 0" :rowspan="item.orderCommodity.length">{{ item.order_type == 1 ? '快递' : '自提' }}</td>
                  <td v-if="item.orderCommodity.length == 1 || l == 0" :rowspan="item.orderCommodity.length">
                    {{ item | getstatustxt }}

                    <!-- <span v-if="item.status == '已收货' || item.status == '已完结'">{{ item.is_evaluate ? '已评价' : '未评价' }}</span> -->
                  </td>
                  <td>
                    <el-button type="text" @click="showOrder(item.id)">查看详情</el-button>
                    <!-- <el-button v-has type="text" v-if="item.status == '待支付' && login_type_url != 'shop'" @click="changeState(item.id)">确认付款</el-button> -->
                    <!-- <el-button  type="text" v-if="item.status == 4" @click="orderClose(item.id)">删除订单</el-button>
                    <el-button  type="text" v-if="item.status == 1" @click="orderdrawback(item.id)">退款</el-button>
 -->
                    <el-button type="text" v-if="item.status == 1" @click="toExpress(item)">确认发货</el-button>
                    <!-- <el-button  type="text"  @click="changeAddress(item)">
                      修改收货信息
                    </el-button> -->
                    <!--    <el-button

                      type="text"
                      v-if="item.status==3"
                      @click="cancalExpress(item.id)"
                    >
                      取消发货
                    </el-button> -->
                  </td>
                </tr>
              </tbody>
            </table>
          </div>
        </div>

        <div class="order_empty" v-if="list.length == 0">暂无数据</div>
      </div>
      <div class="table_footer" style="justify-content: flex-end;" v-if="total != 0">
        <el-pagination @current-change="changePage" class="pages" background hide-on-single-page layout="prev, pager, next" :total="total"></el-pagination>
      </div>
    </div>
    <el-dialog title="订单发货" destroy-on-close :visible.sync="showExpress">
      <el-form size="medium" ref="expressForm" :model="orderExpObj" :rules="itemRules" label-width="100px">
        <el-form-item label="收货人">{{ orderExpObj.consignee }}</el-form-item>
        <el-form-item label="联系电话">{{ orderExpObj.iphone }}</el-form-item>
        <el-form-item label="收货地址">{{ orderExpObj.address }}</el-form-item>

        <el-form-item prop="express_company" label="选择物流">
          <el-select v-model="orderExpObj.express_company" filterable placeholder="请选择物流">
            <el-option v-for="item in expressList" :key="item.id" :label="item.name" :value="item.name"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item prop="logistics_no" label="物流单号"><el-input placeholder="请输入物流单号" v-model="orderExpObj.logistics_no"></el-input></el-form-item>
        <el-form-item><el-button type="primary" @click="saveExp">确定发货</el-button></el-form-item>
      </el-form>
    </el-dialog>
    <!--    <el-dialog>
      <el-form size="medium"  ref="addressForm" :model="obj" :rules="itemRules" label-width="100px">
        <el-form-item label="收货人" prop="consignee"><el-input placeholder="请输入收货人" v-model="obj.consignee"></el-input></el-form-item>

        <el-form-item label="联系电话" prop="iphone"><el-input placeholder="请输入联系号码" v-model="obj.iphone"></el-input></el-form-item>

        <el-form-item label="所在区域" prop="districtSelected">
          <el-cascader
            :disabled="order.status == '待发货' ? true : false"
            :options="options"
            v-model="obj.districtSelected"
            @change="districtSelect"
            ref="location"
            style="width:270px"
          ></el-cascader>
        </el-form-item>

        <el-form-item label="详细地址" prop="address"><el-input placeholder="请输入详细地址" v-model="obj.address"></el-input></el-form-item>

        <el-form-item><el-button type="primary" @click="saveData">保存数据</el-button></el-form-item>
      </el-form>
    </el-dialog> -->
  </el-container>
</template>

<script>
import DatePicker from '@/components/DatePicker/index';
// import orderExpress from './components/orderExpress';
// import orderAddress from './components/orderAddress';
// import orderExpressCancel from './components/orderExpressCancel';
// import {delOrder, getOrderList, orderState, cancelExpress, exportorder, } from '@/api/shop/order';
import {createReceipt, getReceiptTemplateList, getReceiptPrinterList} from '@/api/shop/print';
import {objextend} from '@/utils/index.js';
import {getToken, getShopToken, logintype_byurl} from '@/utils/auth';
import {getorderlist, orderdeliver, orderdrawback, orderClose, getorderdetail} from '@/api/mall/integral';
import {getexpress} from '@/api/shop/freight';
import {regionData, CodeToText, TextToCode} from 'element-china-area-data';
export default {
  data() {
    return {
      rk: 1,
      showCancel: false,
      expressCancel: {},
      showAddress: false,
      options: regionData,
      orderAddressObj: {},
      showExpress: false,
      orderExpObj: {},
      showPrintReceipt: false,
      templateRecList: [],
      templateList: [],
      type: [
        {
          value: '7',
          label: '订单编号'
        },
        {
          value: '1',
          label: '用户ID'
        },
        {
          value: '2',
          label: '用户信息'
        },
        {
          value: '3',
          label: '收件人信息'
        },
        {
          value: '4',
          label: '地址信息'
        },
        {
          value: '5',
          label: '商品名称'
        },
        {
          value: '6',
          label: '商品编号'
        }
      ],
      pay_type: [
        {
          value: '',
          label: '全部'
        },
        {
          value: 1,
          label: '余额'
        },
        {
          value: 2,
          label: '微信'
        },
        {
          value: 3,
          label: '支付宝'
        },
        {
          value: 4,
          label: '后台支付'
        }
      ],
      status: [
        {
          value: '',
          label: '全部'
        },
        {
          value: 1,
          label: '待发货'
        },
        {
          value: 5,
          label: '待核销'
        },
        {
          value: 2,
          label: '已发货'
        },
        {
          value: 3,
          label: '已收货'
        },
        {
          value: 4,
          label: '已关闭'
        }
      ],
      obj: {
        //name:'',
        // type: '7',
        order_no: '',
        pay_type: '',
        status: '',
        start_time: '',
        end_time: '',
        page: 1,
        size: 10
        // order_type:1
      },
      objTemp: {},
      total: 0,
      isLoading: false,
      list: [],
      expressList: [],
      psoRec: {
        order_id: [],
        printer_id: '',
        template_id: ''
      },
      login_type: '',
      login_type_url: '',
      itemRules: {
        express_company: [
          {
            required: true,
            message: '请选择物流'
          }
        ],
        logistics_no: [
          {
            required: true,
            message: '请输入单号'
          }
        ]
      }
    };
  },
  components: {
    DatePicker
  },
  filters: {
    getstatustxt(data) {
      let val = data.status;
      switch (val) {
        case 0:
          return '未付款';
          break;
        case 1:
          return '待发货';
          break;
        case 2:
          return data.order_type == 1 ? '待收货' : '待核销';
          break;
        case 3:
          return '已收货';
        case 4:
          return '已关闭';
          break;
        default:
          return '-';
          break;
      }
    }
  },
  created() {
    this.login_type_url = logintype_byurl();
    if (this.$route.meta && this.$route.meta.status) {
      this.obj.status = this.$route.meta.status;
    }
    if (this.$route.query.status) {
      this.obj = objextend(this.obj, this.$route.query);
    }
    if (this.$route.query.type) {
      this.obj = objextend(this.obj, this.$route.query);
    }
    this.login_type = localStorage.getItem('login_type');
  },
  mounted() {
    this.searchList();
    this.getExpressAll();
  },
  methods: {
    saveExp() {
      this.$refs.expressForm.validate(valid => {
        if (valid) {
          let _data = {
            id: this.orderExpObj.id,
            logistics_no: this.orderExpObj.logistics_no,
            express_company: this.orderExpObj.express_company
          };

          orderdeliver(_data).then(res => {
            this.showExpress = false;
            this.searchList();
          });
        } else {
          return false;
        }
      });
    },
    //获取所有快递
    getExpressAll() {
      getexpress().then(res => {
        this.expressList = res.msg;
      });
    },
    //导出订单
    exportorder() {
      if (localStorage.getItem('login_type') == 'mall') {
        var Authorization = getShopToken();
      } else {
        var Authorization = getToken();
      }
      // Authorization
      let data = this.objTemp;
      if (data.status == '13') {
        data.status = '2';
        data.order_type = 2;
      } else {
        // this.objTemp.order_type=''
      }
      var url = `/shop/order/export?type=${data.type}&keyword=${data.keyword}&pay_type=${data.pay_type}&start_time=${data.start_time}&end_time=${data.end_time}&status=${
        data.status
      }&Authorization=${Authorization}`;
      if (data.order_type) {
        url += `&order_type=${data.order_type}`;
      }
      window.location.href = url;
    },
    orderdrawback(id) {
      this.$confirm('是否直接退款？').then(_ => {
        // this.isLoading = true;
        orderdrawback({id: id}).then(res => {
          // this.isLoading = false;
          this.getDataList();
        });
      });
    },
    //取消发货
    cancalExpress(id) {
      this.showCancel = true;
      this.$nextTick(_ => {
        this.$refs.cancelComponent.init(id);
      });
    },
    //取消发货回调
    cancelSuccess() {
      this.showCancel = false;
      this.getDataList();
    },
    //查看维权详情
    showAfter(id) {
      this.$router.push({path: '/order/list/afterItem', query: {id: id, k: Math.random()}});
    },
    //修改订单状态(临时,测试用,将订单改成'已付款'状态)
    changeState(id) {
      this.$confirm('是否直接修改订单状态为"已支付"?')
        .then(_ => {
          let o = {};
          o.id = id;
          o.status = 2;
          this.isLoading = true;
          orderState(o).then(res => {
            this.isLoading = false;
            this.getDataList();
          });
        })
        .catch({
          //empty
        });
    },
    //修改收货信息
    changeAddress(item) {
      this.orderAddressObj = item;
      this.rk++;
      this.showAddress = true;
    },
    //修改收货信息回调
    closeAddress() {
      this.showAddress = false;
      this.getDataList();
    },
    //确认发货
    toExpress(item) {
      this.orderExpObj = Object.assign({}, item);
      console.log(this.orderExpObj);
      this.rk++;
      this.showExpress = true;
    },
    //发货回调函数
    closeExpress() {
      this.showExpress = false;
      this.getDataList();
    },
    //复制单号
    doCopy(orderNo) {
      this.$copyText(orderNo).then(
        res => {
          //this.$alert('复制成功');
          this.$message({
            message: '复制成功',
            type: 'success',
            duration: 2000
          });
        },
        error => {
          this.$alert('无法复制');
        }
      );
    },
    //获取时间
    getTime(value) {
      this.obj.start_time = value[0];
      this.obj.end_time = value[1];
    },
    //查询数据
    searchList() {
      //复制查询对象
      this.objTemp = Object.assign({}, this.obj);
      this.getDataList();
    },
    //查询数据本体
    getDataList() {
      this.isLoading = true;
      if (this.objTemp.status == '5') {
        this.objTemp.status = '2';
        this.objTemp.order_type = 2;
      } else {
        // this.objTemp.order_type=''
      }
      getorderlist(this.objTemp)
        .then(res => {
          this.isLoading = false;
          let o = res.msg;
          console.log(o.data);
          //处理sku规格数据
          o.data.forEach(e => {
            let x = e.orderCommodity;
            if (x.pvs_value) {
              //转换处理SKU数据->红+L+大
              let l = x.pvs_value.split(','),
                s = '';
              l.forEach(k => {
                s += k.split(':')[1] + '+';
              });
              s = s.substring(0, s.length - 1);
              x.pvs_value_new = s;
            }
            e.orderCommodity = [x];
            if (e.status == '待发货' && e.order_type == 2) {
              e.status = '待核销';
            }
          });
          console.log(o.data);
          this.list = o.data;
          this.total = o.total;
        })
        .catch(e => {
          this.isLoading = false;
        });
    },
    //查看订单详情
    showOrder(id) {
      this.$router.push({path: '/integralgoods/orderitem', query: {id: id, k: Math.random()}});
    },
    //获取所有打印模板(小票)
    getTemplateRecList() {
      getReceiptTemplateList()
        .then(res => {
          this.templateRecList = res.msg;
        })
        .catch(e => {
          //empty
        });
    },
    //获取所有打印模板
    getTemplateList() {
      getReceiptPrinterList()
        .then(res => {
          this.templateList = res.msg;
        })
        .catch(e => {
          //empty
        });
    },
    printReceipt(id) {
      let order_id = [];
      order_id.push(id);
      this.psoRec.order_id = order_id;
      this.showPrintReceipt = true;
    },
    //打印小票关闭自动清空模板选择数据
    clearDataRec() {
      this.psoRec.template_id = '';
      this.psoRec.printer_id = '';
    },
    //打印小票
    printRecFun() {
      if (this.psoRec.template_id && this.psoRec.printer_id) {
        createReceipt(this.psoRec)
          .then(res => {
            this.$message({
              message: '操作完毕,请等待打印结果',
              type: 'success'
            });
            this.showPrintReceipt = false;
          })
          .catch(e => {
            //empty
          });
      } else {
        this.$alert('请先选择打印模板与打印机');
        return false;
      }
    },
    //打印面单
    toprint(order_no) {
      let routeUrl = this.$router.resolve({
        path: '/print/list',
        query: {order_no: order_no}
      });
      window.open(routeUrl.href, '_blank');
    },
    //删除数据
    delItem(id) {
      this.$confirm('是否要删除该条数据?').then(_ => {
        this.isLoading = true;
        delOrder(id)
          .then(res => {
            this.isLoading = false;
            //重新加载数据
            this.getDataList();
          })
          .catch(e => {
            this.isLoading = false;
          });
      });
    },
    orderClose(id) {
      this.$confirm('是否要删除该订单?').then(_ => {
        this.isLoading = true;
        orderClose({id: id})
          .then(res => {
            this.isLoading = false;
            //重新加载数据
            this.getDataList();
          })
          .catch(e => {
            this.isLoading = false;
          });
      });
    },
    //切换分页
    changePage(page) {
      this.objTemp.page = page;
      this.getDataList();
    }
  }
};
</script>

<style lang="scss" scoped>
// .list_con{
//   overflow-x: hidden;
// }
// .orderlist{
//   min-width: 1400px;
// }
.one_line {
  width: 200px;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}
.proImg {
  display: flex;
  align-items: center;
}
.psoRec_item {
  display: flex;
  align-items: center;
  margin-bottom: 22px;

  .label {
    width: 100px;
    text-align: right;
  }

  .content {
    flex-grow: 1;
  }
}
//订单列表
.orderlist {
  width: 100%;
  display: flex;
  flex-direction: column;

  .order_head {
    border-bottom: 1px solid #dcdfe6;
    font-weight: 700;
    color: #909399;
    font-size: 14px;

    table {
      tr {
        td {
          padding: 10px 20px 20px;
          // text-align: center;
        }
      }
    }
  }

  .order_empty {
    color: #c0c4cc;
    font-size: 14px;
    text-align: center;
    height: 50px;
    line-height: 50px;
  }

  .order {
    margin-top: 15px;

    &:first-child {
      margin-top: 0;
    }

    .header {
      background-color: #f4f6f8;
      height: 40px;
      line-height: 40px;
      display: flex;
      border: 1px solid #dcdfe6;
      border-bottom: 0;
      padding-left: 20px;
      color: #909399;
      font-size: 14px;

      .txt {
        flex: 1;
        display: flex;
        .info {
          display: inline-block;
          margin-right: 15px;
        }
      }

      .button {
        width: 200px;
        text-align: right;
        padding-right: 20px;
      }
    }

    .content {
      background: #dcdfe6;
      font-size: 14px;
      color: #606266;

      table {
        background: #fff;

        tr {
          td {
            padding: 17px 17px 0 17px;
            line-height: 28px;
            //border: 1px solid #DCDFE6;
            border: none;
            .pro {
              display: flex;

              .img {
                width: 80px;
                height: 80px;
                margin-right: 10px;
              }

              .txt {
                flex: 1;
                display: flex;
                flex-direction: column;
                align-content: space-between;

                .name {
                  .t0 {
                    color: #409eff;
                    font-weight: 700;
                    margin-right: 5px;
                  }

                  .t1 {
                    color: #f56c6c;
                    font-weight: 700;
                    margin-right: 5px;
                  }
                }
              }
            }
          }
          &:last-child {
            td {
              padding: 17px;
            }
          }
        }
      }
    }
  }
}
</style>
